package com.csw.shuanfa.utils.maven;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 1
 */
@Slf4j
public class fileOperateUtils {

    public static void main(String[] args) {

        // renameDirFiles(pathString, "class", "java");

        //删除空白文件夹
//        String pathString = "D:\\";
//        deleteEmptyDir(pathString);
//        moveDir2(pathString);

        String pathString = "D:\\BaiduNetdiskDownload\\亿级流量电商详情页系统实战（第二版）：缓存架构+高可用服务架构+微服务架构(13GB)";
        changeVideoName(pathString, "课程视频.avi", 2);
    }

    /**
     * 视频名字相同重命名
     * String pathString = "D:\\BaiduNetdiskDownload\\亿级流量电商详情页系统实战（第二版）：缓存架构+高可用服务架构+微服务架构(13GB)";
     * changeVideoName(pathString, "课程视频.avi", 2);
     */
    public static void changeVideoName(String path, String videoName, int index) {
        File file = new File(path);
        File[] files = file.listFiles();
        for (File file1 : files) {
            if (file1.isDirectory()) {
                changeVideoName(file1.getPath(), videoName, index);
            } else if (file1.isFile()) {
                if (videoName.equals(file1.getName())) {
                    String path0 = getPath(index, file1);
                    String fil1Name = file1.getName();
                    String suffFix = fil1Name.substring(fil1Name.lastIndexOf(".") + 1);
                    String endPath = file1.getParent() + "\\" + new File(path0).getName() + "." + suffFix;
                    System.out.println(endPath);
                    file1.renameTo(new File(endPath));
                }
            }
        }
    }

    static String getPath(int index, File file) {
        if (index > 0) {
            String path = file.getParent();
            index--;
            if (index > 0) {
                return getPath(index, new File(path));
            } else if (index == 0) {
                return path;
            }
        }
        return "";
    }

    /**
     * #################################################################################################################
     * 将文件夹asd/asd/aa.txt变成asd/aa.txt
     *
     * @param pathName 路径
     */
    public static void moveDir2(String pathName) {
        log.error("进入{}", pathName);
        if (pathName.indexOf("\\$") > 0 || pathName.indexOf("Volume") > 0 || pathName.indexOf("repository") > 0) {
            return;
        }

        File file = new File(pathName);
        /* 1,获取该文件夹下的所有的文件和文件夹 */
        File[] subFiles = file.listFiles();
        /* 2,遍历数组 */
        if (subFiles.length == 0) {
            file.delete();
            return;
        }
        for (File file0 : subFiles) {
            if (subFiles.length == 1 && file0.isDirectory()) {
                //如果二级文件夹目录和一级文件夹目录相同,要移动
                if (file.getName().equals(file0.getName())) {
                    File[] files = file0.listFiles();
                    //比如a下面有a,b的情况不考虑
                    if (files.length == 0) {
                        file0.delete();
                        return;
                    }

                    //将二级文件夹下面进行遍历三级文件夹,要移动的文件夹内容
                    Map<String, String> map = new HashMap<>();
                    for (File file1 : files) {
                        String newlines1 = file.getPath() + "\\" + file1.getName();
                        //如果一级目录和三级目录有重名
                        if (file.getName().equals(file1.getName())) {
                            String newLine_ = newlines1 + "_";
                            map.put(newLine_, newlines1);
                            new File(file1.getPath()).renameTo(new File(newLine_));
                            log.error("{}", newlines1);
                        } else {
                            new File(file1.getPath()).renameTo(new File(newlines1));
                            log.error("{}", newlines1);
                        }
                    }
                    file0.delete();
                    //在删除完之后进行文件名还原
                    for (String aa : map.keySet()) {
                        new File(aa).renameTo(new File(map.get(aa)));
                    }
                    //然后继续往下遍历
                    moveDir2(file.getPath());

                } else {
                    //继续遍历ab
                    moveDir2(file0.getPath());
                }

            } else if (subFiles.length > 1 && file0.isDirectory()) {
                //有多个文件并且当前文件也是目录，则继续遍历
                moveDir2(file0.getPath());
            }

        }

    }

    /**
     * #################################################################################################################
     * 将文件或文件夹中的一二三等全部替换为123
     *
     * @param pathName 路径
     */
    public static void replace123(String pathName) {
        log.error("{}", pathName);
        File file = new File(pathName);
        File newFile = newFilePath(file);
        /* 1,获取该文件夹下的所有的文件和文件夹 */
        File[] subFiles = newFile.listFiles();
        /* 2,遍历数组 */
        if (subFiles.length != 0) {
            for (File subFile : subFiles) {
                if (subFile.isFile()) {
                    //如果是文件就重命名
                    newFilePath(subFile);
                } else {
                    //如果是文件夹就循环调用
                    replace123(subFile.getPath());
                }
            }
        }
    }

    /**
     * #################################################################################################################
     * 对文件重命名
     *
     * @param subFile
     */
    private static File newFilePath(File subFile) {
        String path00String = subFile.getName();
        path00String = path00String.replace("一", "1").replace("二", "2").replace("三", "3")
                .replace("四", "4").replace("五", "5").replace("六", "6")
                .replace("七", "7").replace("八", "8").replace("九", "9");
        boolean isTen = path00String.contains("十");
        if (isTen) {
            int asd = path00String.indexOf("十");
            int lastIndex = path00String.length() - 1;
            //是否第一个字符
            boolean first = false;
            if (asd == 0) {
                first = true;
            }
            //是否最后一个字符
            boolean last = false;
            if (asd == lastIndex) {
                last = true;
            }
            if (first && last) {
                //左右都没有
                path00String = path00String.replace("十", "10");
            } else if (first && !last) {
                //左没有右有
                char lastP = path00String.charAt(asd + 1);
                if (isNumber(lastP + "")) {
                    path00String = path00String.replace("十", "1");
                } else {
                    path00String = path00String.replace("十", "10");
                }
            } else if (!first && last) {
                //左有右没有
                char firstP = path00String.charAt(asd - 1);
                if (isNumber(firstP + "")) {
                    path00String = path00String.replace("十", "0");
                } else {
                    path00String = path00String.replace("十", "10");
                }
            } else if (!first && !last) {
                //左右都有
                char firstP = path00String.charAt(asd - 1);
                char lastP = path00String.charAt(asd + 1);
                if (isNumber(firstP + "") && isNumber(lastP + "")) {
                    path00String = path00String.replace("十", "");
                } else if (!isNumber(firstP + "") && isNumber(lastP + "")) {
                    path00String = path00String.replace("十", "1");
                } else if (isNumber(firstP + "") && !isNumber(lastP + "")) {
                    path00String = path00String.replace("十", "0");
                } else if (!isNumber(firstP + "") && !isNumber(lastP + "")) {
                    path00String = path00String.replace("十", "10");
                }

            }

        }
        File newFile = new File(subFile.getParent() + "\\" + path00String);
        subFile.renameTo(newFile);
        return newFile;

    }

    /**
     * #################################################################################################################
     * 是数字
     *
     * @param str
     * @return
     */
    public static boolean isNumber(String str) {
        for (int i = 0; i < str.length(); i++) {
            if (!(str.charAt(i) >= '0' && str.charAt(i) <= '9')) {
                return false;
            }
        }
        return true;
    }

    /**
     * #################################################################################################################
     * 删除文件夹及其里面的文件和文件夹
     *
     * @param pathName 路径
     */
    public static void deleteDir(String pathName) {
        log.error("{}", pathName);
        File file = new File(pathName);
        /* 1,获取该文件夹下的所有的文件和文件夹 */
        File[] subFiles = file.listFiles();
        /* 2,遍历数组 */
        if (subFiles.length != 0) {
            for (File subFile : subFiles) {
                String path00String = subFile.getPath();
                log.error("是不是文件路劲{}", path00String);
                /* 3,判断是文件直接删除 */
                if (subFile.isFile()) {
                    log.error("是文件");
                    if (!subFile.delete()) {
                        //do something
                    }
                    /* 4,如果是文件夹,递归调用 */
                } else {
                    log.error("是文件夹");
                    deleteDir(subFile.getPath());
                }
            }
        } else {
            /* 如果上来就是一个空文件夹就直接删除 */
            if (!file.delete()) {

            }
        }
    }

    /**
     * #################################################################################################################
     * 删除空文件夹
     */
    public static void deleteEmptyDir(String pathName) {
        log.error("进入{}", pathName);
        if (pathName.indexOf("\\$") > 0 || pathName.indexOf("Volume") > 0) {
            return;
        }
        File file = new File(pathName);
        /* 1,获取该文件夹下的所有的文件和文件夹 */
        File[] subFiles = file.listFiles();
        /* 2,遍历数组 */
        if (subFiles.length != 0) {
            for (File subFile : subFiles) {
                String path00String = subFile.getPath();
                /* 3,判断是文件直接删除 */
                if (subFile.isDirectory()) {
                    deleteEmptyDir(path00String);
                }
            }
        } else {
            /* 如果上来就是一个空文件夹就直接删除 */
            dirRoundDelete(pathName);
        }
    }

    /**
     * #################################################################################################################
     * 空文件夹往上循环删除
     *
     * @param path
     */
    public static void dirRoundDelete(String path) {
        File file = new File(path);
        File[] subFiles = file.listFiles();
        if (file.isDirectory() && subFiles.length == 0) {
            String parPath = file.getParent();
            file.delete();
            log.info("删除文件夹{}", file.getPath());
            dirRoundDelete(parPath);
        }
    }

    /**
     * #################################################################################################################
     * 将一个文件夹里面的文件名后缀批量修改
     *
     * @param pathName          文件夹路径
     * @param oldFileSuffexName 老文件名后缀
     * @param newFileSuffexName 新文件名后缀
     */
    public static void renameDirFiles(String pathName, String oldFileSuffexName, String newFileSuffexName) {
        log.info("{}", pathName);
        File file = new File(pathName);
        /* 1,获取该文件夹下的所有的文件和文件夹 */
        File[] subFiles = file.listFiles();
        /* 2,遍历数组 */
        if (subFiles.length != 0) {
            for (File subFile : subFiles) {
                /* 3,判断是文件直接删除 */
                if (subFile.isFile()) {
                    String fileName0String = subFile.getName();
                    String suffexString = fileName0String.substring(fileName0String.lastIndexOf(".") + 1);
                    if (oldFileSuffexName.equals(suffexString)) {
                        String firString = fileName0String.substring(0, fileName0String.lastIndexOf("."));
                        String newFilePath = subFile.getParent() + "\\" + firString + "." + newFileSuffexName;
                        File newFile = new File(newFilePath);
                        if (!subFile.renameTo(newFile)) {
                            //do something
                        }
                    }
                    /* 4,如果是文件夹,递归调用 */
                } else {
                    renameDirFiles(subFile.getPath(), oldFileSuffexName, newFileSuffexName);
                }
            }
        }
    }


    /**
     * #################################################################################################################
     * 清理maven仓库的老版本依赖
     *
     * @param pathName 仓库文件夹路径
     * @throws Exception
     */
    public static void deleteOldDependenceVersion(String pathName) {
        log.info("{}", pathName);
        File file = new File(pathName);
        File[] files = file.listFiles();

        /* 判断当前目录下是不是带版本号掉文件夹 */
        /* 初始版本号大小 */
        String maxFileName = "0";
        boolean isVersionBoolean = false;
        if (files.length != 0) {
            for (File file0 : files) {
                String dirName0 = file0.getName();
                /* 判断子文件夹开头是不是带版本号 */
                boolean digit = Character.isDigit(dirName0.charAt(0));
                boolean isDirBoolean = file0.isDirectory();
                String file0PathString = file0.getPath();
                /* 是文件夹，开头带版本号 */
                if (isDirBoolean && digit) {
                    isVersionBoolean = true;
                    try {
                        if (compareVersion(dirName0, maxFileName) > 0) {
                            maxFileName = dirName0;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    /* 是普通文件夹就继续循环遍历 */
                } else if (isDirBoolean) {
                    /* 递归遍历文件夹中是否还有文件夹 */
                    deleteOldDependenceVersion(file0PathString);
                }
            }
            if (isVersionBoolean) {
                for (File file1 : files) {
                    boolean isDirBoolean = file1.isDirectory();
                    String dirName0 = file1.getName();
                    if (!dirName0.equals(maxFileName) && isDirBoolean) {
                        String file1PathString = file1.getPath();
                        deleteDir(file1PathString);
                    }
                }
            }
        } else {
            if (!file.delete()) {
                //dosomething
            }
        }

    }

    /**
     * #################################################################################################################
     * 比较版本号的大小,前者大则返回一个正数,后者大返回一个负数,相等则返回0 规则是按日期订的例如：2.10.15 项目启动第2年的8月15号
     *
     * @param version1
     * @param version2
     * @return int
     */
    public static int compareVersion(String version1, String version2) throws Exception {
        if (version1 == null || version2 == null) {
            throw new Exception("compareVersion error:illegal params.");
        }
        /* 注意此处为正则匹配，不能用"."； */
        String[] versionArray1 = getVersionArray(version1);
        String[] versionArray2 = getVersionArray(version2);
        int idx = 0;
        /* 取最小长度值 */
        int minLength = Math.min(versionArray1.length, versionArray2.length);
        int diff = 0;
        /* 先比较长度 */
        /* 再比较字符 */
        while (idx < minLength && (diff = versionArray1[idx].length() - versionArray2[idx].length()) == 0
                && (diff = versionArray1[idx].compareTo(versionArray2[idx])) == 0) {
            ++idx;
        }
        /* 如果已经分出大小，则直接返回，如果未分出大小，则再比较位数，有子版本的为大； */
        diff = (diff != 0) ? diff : versionArray1.length - versionArray2.length;
        return diff;
    }

    private static String[] getVersionArray(String ver) {
        String[] versionArray;
        versionArray = ver.split("\\.");
        /* 如果位数只有一位则自动补零（防止出现一个是04，一个是5 直接以长度比较） */
        for (int i = 0; i < versionArray.length; i++) {
            if (versionArray[i].length() == 1) {
                StringBuilder chuShi = new StringBuilder();
                versionArray[i] = chuShi.append("0").append(versionArray[i]).toString();
            }
        }
        return versionArray;
    }

}
